# Descobre hora correta via NTP
# e cria o arquivo ajustarelogio.nsh que
# deve ser chamado para configurar o relogio

from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time

sys.path.append(os.path.dirname(__file__))
from URLs import *

# # Set the socket parameters 

host = URLs[os.environ["LOCATION"]]['ntp']
port = 123
buf = 1024
address = (host,port)
msg = '\x1b' + 47 * '\0' 

# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00

# connect to server
try:
	client = socket.socket( AF_INET, SOCK_DGRAM)
	client.sendto(msg, address)
	msg, address = client.recvfrom( buf )
	client.close()
	t = struct.unpack( "!12I", msg )[10]
	t -= TIME1970

	tm = time.localtime(t)

	with open('./ajustarelogio.nsh', 'w') as f:
		f.write('date %02d/%02d/%04d\r\n' % (tm.tm_mon, tm.tm_mday, tm.tm_year))
		f.write('time %02d:%02d:%02d' % (tm.tm_hour, tm.tm_min, tm.tm_sec))

	print "NTP.py - Data atual: %s" % time.ctime(t)
except socket.error, (value,message):
	print "Erro ao acessar servidor NTP %s" % host
	sys.exit(-1)
